package com.mofro.jdbc;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import com.mofro.core.MofroException;

/**
 * Proveedor de conexiones a la base de datos Oracle.
 * 
 * @author achevali
 *
 */
public class ConnectionManager {
	
	private static ResourceBundle properties;
	
	private static final String URL_PROPERTY_KEY = "jdbc.?.url";
	private static final String USERNAME_PROPERTY_KEY = "jdbc.?.username";
	private static final String PASSWORD_PROPERTY_KEY = "jdbc.?.password";

	/**
	 * Devuelve una conexi&oacute;n a la base de datos Oracle.
	 * 
	 * @param schemaName el nombre del esquema, con el cual se busca en el archivo de propiedades
	 * @return conexi&oacute;n a la base de datos
	 * @throws MofroException
	 */
	public static MofroConnection getConnection(String schemaName) throws MofroException {
		Connection connection = null;
	    try {
	        // Load the JDBC driver
	        String driverName = "oracle.jdbc.driver.OracleDriver";
	        Class.forName(driverName);	        
	    
	        // Create a connection to the database
	        String url = getUrl(schemaName);
	        String username = getUsername(schemaName);
	        String password = getPassword(schemaName);
	        connection = DriverManager.getConnection(url, username, password);
	    } 
	    catch (ClassNotFoundException e) {
	    	throw new MofroException("Could not find the database driver", e);
	    } 
	    catch (SQLException e) {
	        throw new MofroException("Could not connect to the database", e);
	    }
	    return new MofroConnection(connection);
	}
	
	/**
	 * Levanta las propiedades del archivo de configuraci&oacute;n.
	 * 
	 * @param resourceName nombre del archivo de propiedades
	 * @throws IOException
	 * @throws MofroException 
	 */
	public synchronized static void loadProperties(String resourceName) throws MofroException {
		if (properties == null) {
			try {
				properties = ResourceBundle.getBundle(resourceName);
			} 
			catch (MissingResourceException e) {
				throw new MofroException("Can not find " + resourceName + " file");
			}			
		}
	}
	
	private static String getUrl(String schemaName) {
		String key = URL_PROPERTY_KEY.replace("?", schemaName);		
		return properties.getString(key);
	}
	
	private static String getUsername(String schemaName) {
		String key = USERNAME_PROPERTY_KEY.replace("?", schemaName);		
		return properties.getString(key);
	}
	
	private static String getPassword(String schemaName) {
		String key = PASSWORD_PROPERTY_KEY.replace("?", schemaName);		
		return properties.getString(key);
	}
}
